#ifndef _CAMERA_H_
#define _CAMERA_H_

#include "timer.h"
#include "vector2.h"
#include "Sprite.h"
#include "iostream"
class Camera
{
public:
	Camera(int width,int height)
	{
		viewSize.x = width;
		viewSize.y = height;
		timer_shake.set_one_shot(true);
		timer_shake.set_callback([&]()
			{	
				Vector2 old_pos = position;
				std::cout << old_pos.x << old_pos.y << std::endl;
				is_shaking = false;
				Set(old_pos);
				//reset();
			});
	}

	~Camera() = default;

	//获取当前相机偏移
	const Vector2& get_position() const
	{
		return position;
	}

	void reset()
	{
		position.x = 0;
		position.y = 0;
	}


	//每帧更新相机位置
	void on_update(int delta)
	{
		timer_shake.on_update(delta);

		if (is_shaking)
		{
			position.x =position.x + (-50 + rand() % 100) / 50.0f * shaking_strength;
			position.y = position.y + (-50 + rand() % 100) / 50.0f * shaking_strength;
			std::cout << position.x<< "     " << position.y << std::endl;

		}
	}

	//实现屏幕震动
	void shake(float strength, int duration)
	{	
		is_shaking = true;
		shaking_strength = strength;

		timer_shake.set_wait_time(duration);
		timer_shake.restart();
	}

	// 计算摄像头应移动到的目标位置（角色居中）
	Vector2 CalculateTargetPosition(Vector2 character) {
		// 目标位置 = 角色位置 - 视口尺寸的一半
		Vector2 targetPosition;
		targetPosition.x = character.x - viewSize.x / 2;
		targetPosition.y = character.y - viewSize.y / 2;
		return targetPosition;
	}

	void Move(Vector2& character) {
		Vector2 targetPosition = CalculateTargetPosition(character);
		position = targetPosition;
	}

	void Set(Vector2 pos) {
		position = pos;
	}

	// 线性插值（Lerp）移动
	void SmoothCameraMovement(Vector2& character, float speed) {
		// 计算插值后的新位置
		Vector2 targetPosition = CalculateTargetPosition(character);
		Vector2 newPosition;
		newPosition.x = Lerp(position.x, targetPosition.x, smoothSpeed * speed);
		newPosition.y = Lerp(position.y, targetPosition.y, smoothSpeed * speed);
		//// 更新摄像头位置
		position = newPosition;
	}

	// 线性插值函数
	float Lerp(float a, float b, float t) {
		return a + t * (b - a);
	}
private:
	//Vector2 old_pos;
	Vector2 position;
	Timer timer_shake;
	Vector2 viewSize;
	bool is_shaking = false;
	float shaking_strength = 0;
	float smoothSpeed = 0.05f;
};

#endif // !_CAMERA_H_
